package com.myimooc.shiro.web.controller;

import com.myimooc.shiro.web.constant.Constants;
import com.myimooc.shiro.web.vo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @className: UserController
 * @description: 处理用户相关请求
 * @date: 2020/5/12
 * @author: cakin
 */
@Controller
public class UserController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @GetMapping("/403")
    public String to403() {
        return "403";
    }

    /**
     * 功能描述：
     *
     * @author cakin
     * @date 2020/5/12
     * @param user 用户信息
     * @return String
     */
    @PostMapping("/subLogin")
    @ResponseBody
    public String subLogin( User user ) {
        // 获得主体
        Subject subject = SecurityUtils.getSubject();
        // 前端传过来用户信息封装成token
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            // 设置自动登录
            token.setRememberMe(user.getRememberMe());
            // 认证
            /**
             * 用户名：Tom 密码：123456  查的是users表
             */
            subject.login(token);
        } catch (AuthenticationException e) {
            return e.getMessage();
        }
        // 到数据库user_roles中查询Tom是否有admin的的权限
        if (subject.hasRole(Constants.Role.ADMIN)) {
            return "有admin权限";
        }

        return "无admin权限";
    }

    /**
     * 功能描述：测试角色授权
     *
     * @author cakin
     * @date 2020/5/12
     * @return String
     */
    @GetMapping("/testRole")
    @ResponseBody
    public String testRole() {
        return "testRole Success";
    }

    /**
     * 功能描述：测试角色授权
     *
     * @author cakin
     * @date 2020/5/12
     * @return String
     */
    @GetMapping("/testRole1")
    @ResponseBody
    public String testRole1() {
        return "testRole1 Success";
    }

    /**
     * 功能描述：测试授权
     *
     * @author cakin
     * @date 2020/5/12
     * @return String
     */
    @GetMapping("/testPerms")
    @ResponseBody
    public String testPerms() {
        return "testPerms Success";
    }
    /**
     * 功能描述：测试授权
     *
     * @author cakin
     * @date 2020/5/12
     * @return String
     */
    @GetMapping("/testPerms1")
    @ResponseBody
    public String testPerms1() {
        return "testPerms1 Success";
    }
}
